package com.centling.smartSealForPhone.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.constants.UserType;
import com.centling.smartSealForPhone.db.UpWarnInfo;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.wsdk.service.BluetoothLeService;
import com.wsdk.util.StampUtil;

import java.util.HashMap;
import java.util.Map;

public class StampTimeLimitActivity
        extends TitleBarActivity {

    private ImageView ivStamp;

    private StampUtil stampUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_stamp_count_limit);

        try {
            stampUtil = new StampUtil(this, new StampUtil.StampCallback() {
                @Override
                public void onRemainTimesCallback(int code, int times) {
                    // ignored CountLimit
                }

                @SuppressLint("SetTextI18n")
                @Override
                public void onTimeLimitCallback(int code, String startTime, String endTime) {
                    TextView tvTimes = findViewById(R.id.tv_stamp_times_times);
                    tvTimes.setText("用印开始时间: " + startTime + "\n" + "用印结束时间: " + endTime);
                }

                @Override
                public void onSucessCallback(int code, String msg) {
                    switch (code) {
                        case StampUtil.StampCallback.ERR_STAMP_SUCCESS:
                            enableStampOperation();
                            break;
                        default:
                            break;
                    }
                }

                @Override
                public void onErrorCallback(int code, String msg) {
                    switch (code) {
                        default:
                            enableStampOperation();
                            break;
                    }
                    if (code == StampUtil.StampCallback.ERR_STAMP_NONE_BLE_OPEN) {
                        mActivity.finish();
                    }
                }

                @Override
                public void onProgressCallback(int code, String msg) {
                    switch (code) {
                        case StampUtil.StampCallback.ERR_STAMP_PREPARE_PROGRESS:
                            disableStampOperation();
                            break;
                        case StampUtil.StampCallback.ERR_STAMP_ROLLBACK_PROGRESS:
                        case StampUtil.StampCallback.ERR_STAMP_ROLLBACK_PROGRESS_IGNORE:
                            enableStampOperation();
                        default:
                            break;
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            stampUtil.setSealApplyId(bundle.getString("sealApplyId"));
            macAddress = bundle.getString("macAddress");
            stampUtil.setMacAddress(macAddress);
            sn = bundle.getString("equipSn");
            stampUtil.setSn(sn);

            stampUtil.setStartTime(bundle.getString("sealApplyStartTime"));
            stampUtil.setEndTime(bundle.getString("sealApplyEndTime"));
        }

        setTitleBarText("限时用印");

        initView();
    }

    private void initView() {
        ivStamp = findViewById(R.id.iv_stamp_times_stamp);
        ivStamp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickToStamp();
            }
        });
        TextView tvExit = findViewById(R.id.tv_stamp_times_exit);
        tvExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Button ivStopStamp = findViewById(R.id.iv_stamp_stop_stamp);
        ivStopStamp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickToStopStamp();
            }
        });

        stampUtil.prepareStampEnv();
    }

    private void enableStampOperation() {
        ivStamp.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.prints));
        ivStamp.setClickable(true);
    }

    private void disableStampOperation() {
        ivStamp.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.prints1));
        ivStamp.setClickable(false);
    }

    private void clickToStamp() {
        stampUtil.stamp();
    }

    private void clickToStopStamp(){
        ShowDialog.showSelectDialog(mContext, "警告", "确定将结束用印，剩余次数无法使用", "", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, String> param = new HashMap<>();
                param.put("sealApplyId", stampUtil.getSealApplyId());
                postJsonEnqueue(UrlConstants.STOP_STAMP, param, new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        finish();
                    }

                    @Override
                    public void onFailed(String reason) {
                        ShowToast.shortTime("提前结束用印失败，请重试");
                    }
                });
            }
        });
    }

    private AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption = null;
    private AMapLocationListener aMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    stampUtil.setLongitude(amapLocation.getLongitude());
                    stampUtil.setLatitude(amapLocation.getLatitude());
                    stampUtil.setLocationName(amapLocation.getAddress());
                } else {
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    private void initLocation() {
        mLocationClient = new AMapLocationClient(mContext);
        mLocationClient.setLocationOption(getAMapDefaultLocationOption());
        mLocationClient.setLocationListener(aMapLocationListener);
        mLocationClient.startLocation();
    }

    public AMapLocationClientOption getAMapDefaultLocationOption() {
        if (mLocationOption == null) {
            mLocationOption = new AMapLocationClientOption();
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setNeedAddress(true);
            mLocationOption.setInterval(3000);
            mLocationOption.setKillProcess(true);
        }

        return mLocationOption;
    }

    @Override
    public void onStart() {
        super.onStart();
        initLocation();
    }

    @Override
    public void onStop() {
        super.onStop();
        mLocationClient.unRegisterLocationListener(aMapLocationListener);
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stopLocation();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.onDestroy();
        if (TextUtils.equals(UserType.EQUIP_COMMON_USER, SPUtil.getString(SPConstants.USER_TYPE))
                || TextUtils.equals(UserType.EQUIP_OA_USER, SPUtil.getString(SPConstants.USER_TYPE))) {
            BluetoothLeService.disconnect();
        }
        UpWarnInfo.upgrandWarnInfo();

        if (stampUtil != null) {
            stampUtil.release();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (stampUtil != null) {
            stampUtil.onActivityResult(requestCode, resultCode, data);
        }
    }
}
